package spring.cloud.tasks.api.vo;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import spring.cloud.tasks.api.domain.task.TaskConfiguration;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Setter
@Getter
public class UpdateJobConfigVo {

    private String taskId;
    private String jobClass;
    private Integer shardingTotalCount;
    private String timeZone;
    private String cron;
    private String pausePeriodDate;
    private String pausePeriodTime;
    private String shardingItemParameters;
    private String jobParameter;
    private Integer processCountIntervalSeconds;
    private Boolean failover;
    private String description;
    private Integer timeout4AlarmSeconds;
    private Integer timeoutSeconds;
    private Integer disableTimeoutSeconds;
    private Boolean showNormalLog;
    private String channelName;
    private String jobType;
    private String queueName;
    private Integer loadLevel;
    private Integer jobDegree;
    private Boolean enabledReport;
    private Boolean enabled;
    private String preferList;

    private Boolean localMode;
    private Boolean useSerial;
    private String jobMode;
    private String dependencies;

    private Boolean rerun;
    private String upStream;
    private String downStream;

    public TaskConfiguration toTaskConfiguration() {
        TaskConfiguration taskConfiguration = new TaskConfiguration();
        Map<String, Object> reqParams = new HashMap<>();
        constructJobConfigOfUpdate(taskConfiguration, taskId, reqParams);
        return taskConfiguration;
    }

    private TaskConfiguration constructJobConfigOfUpdate(TaskConfiguration taskConfiguration, String taskId, Map<String, Object> reqParams)
            throws RuntimeException {

        if (!reqParams.containsKey("jobConfig")) {
            throw new RuntimeException(String.format("jobConfig", "cannot be blank"));
        }


        taskConfiguration.setTaskId(taskId);

        taskConfiguration.setDescription((String) reqParams.get("description"));


        taskConfiguration.setCronExpression((String) reqParams.get("cron"));

        taskConfiguration.setTaskParameter((String) reqParams.get("jobParameter"));

        taskConfiguration.setLoadLevel((Integer) reqParams.get("loadLevel"));


        taskConfiguration.setPausePeriodDate((String) reqParams.get("pausePeriodDate"));

        taskConfiguration.setPausePeriodTime((String) reqParams.get("pausePeriodTime"));

        taskConfiguration.setPreferExecutorIdList((String) reqParams.get("preferList"));


        taskConfiguration.setTaskItemParameters((String) reqParams.get("shardingItemParameters"));

        taskConfiguration.setTaskItemTotalCount((Integer) reqParams.get("shardingTotalCount"));


        taskConfiguration.setTimeoutSeconds((Integer) reqParams.get("timeoutSeconds"));


        return taskConfiguration;
    }
}
